package com.maotai.app.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.maotai.app.bean.CustomAppName;
import com.maotai.app.bean.MaotaiAppCookie;

public class MaotaiAppHttpClientUtil {
	
	private static MaotaiAppHttpClientUtil instance = null;

	private MaotaiAppHttpClientUtil() {
	}

	public static MaotaiAppHttpClientUtil getInstance() {
		if (instance == null) {
			instance = new MaotaiAppHttpClientUtil();
		}
		return instance;
	}
	public MaotaiAppCookie sendHttpGetProxy(String httpUrl,MaotaiAppCookie mwc, RequestConfig config,String referer) {
		HttpGet httpGet = new HttpGet(httpUrl);
		httpGet = setHttpGetHeader(httpGet,mwc,referer);
		return sendHttpGetProxy(httpGet,mwc,config);
	}
	/**
	 * 
	 * @param httpUrl
	 */
	private MaotaiAppCookie sendHttpGetProxy(HttpGet httpGet,MaotaiAppCookie mwc, RequestConfig config) {
		CloseableHttpClient httpClient = null;
		CloseableHttpResponse response = null;
		HttpEntity entity = null;
		String return_str = null;
		try {
			httpClient = HttpClients.createDefault();
			
			httpGet.setConfig(config);
			response = httpClient.execute(httpGet);
			entity = response.getEntity();
			return_str = EntityUtils.toString(entity, "UTF-8");
			mwc.setContent(return_str);
			System.out.println(return_str);
		} catch (Exception e) {
//			e.printStackTrace();
		} finally {
			try {
				if (response != null) {
					response.close();
				}
				if (httpClient != null) {
					httpClient.close();
				}
			} catch (IOException e) {
//				e.printStackTrace();
			}
		}
		return mwc;
	}
	private HttpGet setHttpGetHeader(HttpGet httpGet,MaotaiAppCookie mwc,String referer) {
		httpGet.addHeader("Accept","application/json");
		httpGet.addHeader("appcode","2");
		httpGet.addHeader("Accept-Encoding", "gzip");
		httpGet.addHeader("Connection", "keep-alive");
		httpGet.addHeader("Host", "i.cmaotai.com");
		httpGet.addHeader("tenantid", "1");
		httpGet.addHeader("channelcode", "02");
//		httpGet.addHeader("channelCode", "01");
		httpGet.addHeader("terminaltype", "d1");
		httpGet.addHeader("Content-Type","application/x-www-form-urlencoded");
		httpGet.addHeader("User-Agent","okhttp/3.6.0");
		httpGet.addHeader("reqid",System.currentTimeMillis()+"");
		if(mwc.getAuth()!=null && !"".equals(mwc.getAuth())){
			httpGet.addHeader("auth",mwc.getAuth());
		}
		if(mwc.getAcwTc()!=null && !"".equals(mwc.getAcwTc())){
			httpGet.addHeader("Cookie",mwc.getAcwTc());
		}
		if(mwc.getMemberid()!=null && !"".equals(mwc.getMemberid())){
			httpGet.addHeader("memberid",mwc.getMemberid());
		}
		return httpGet;
	}
	private HttpPost setHttpPostHeader(HttpPost httpPost, MaotaiAppCookie mwc ,String referer) {
		httpPost.addHeader("Accept","application/json");
		httpPost.addHeader("appcode","2");
		httpPost.addHeader("Accept-Encoding", "gzip");
		httpPost.addHeader("Connection", "keep-alive");
		httpPost.addHeader("Host", "i.cmaotai.com");
		httpPost.addHeader("tenantid", "1");
		httpPost.addHeader("channelcode", "02");
		httpPost.addHeader("terminaltype", "d1");
		httpPost.addHeader("Content-Type","application/x-www-form-urlencoded");
		httpPost.addHeader("User-Agent","okhttp/3.6.0");
		httpPost.addHeader("reqid",System.currentTimeMillis()+"");
		if(mwc.getAuth()!=null && !"".equals(mwc.getAuth())){
			httpPost.addHeader("auth",mwc.getAuth());
		}
		if(mwc.getAcwTc()!=null && !"".equals(mwc.getAcwTc())){
			httpPost.addHeader("Cookie",mwc.getAcwTc());
		}
		if(mwc.getMemberid()!=null && !"".equals(mwc.getMemberid())){
			httpPost.addHeader("memberid",mwc.getMemberid());
		}
		return httpPost;
	}

    public MaotaiAppCookie sendHttpPostProxy(String httpUrl,MaotaiAppCookie mwc, Map<String, String> maps,RequestConfig requestConfig, String referer) throws Exception {  
        HttpPost httpPost = new HttpPost(httpUrl);
        httpPost = setHttpPostHeader(httpPost,mwc,referer);
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();  
        for (String key : maps.keySet()) {  
            nameValuePairs.add(new BasicNameValuePair(key, maps.get(key)));  
        }  
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));  
        return sendHttpPostProxy(httpPost,mwc,requestConfig);  
    }
    
    private MaotaiAppCookie sendHttpPostProxy(HttpPost httpPost,MaotaiAppCookie mwc,RequestConfig config) throws Exception{  
        CloseableHttpClient httpClient = null;  
        CloseableHttpResponse response = null;  
        HttpEntity entity = null;
		String return_str = null;
        httpClient = HttpClients.createDefault(); 
        httpPost.setConfig(config);  
        response = httpClient.execute(httpPost); 
        entity = response.getEntity();
		return_str = EntityUtils.toString(entity, "UTF-8");
		mwc.setContent(return_str);
		System.out.println(return_str);
        Header[] headers = response.getAllHeaders();
        if(headers!=null&&headers.length>0){
        	for (Header hea : headers) {
//        		System.out.println(hea.getName() + "::::::::::::::"
//						+ hea.getValue());
				if(hea.getName().contains("auth")){
					mwc.setAuth(hea.getValue());
				}
			}
        }
        if (response != null) {  
            response.close();  
        }  
        if (httpClient != null) {  
            httpClient.close();  
        }  
        return mwc;  
    } 
	/**
	 * 发送 get请求
	 * 
	 * @param httpUrl
	 * @throws Exception 
	 */
    public JSONObject getAddress(String address) throws UnsupportedEncodingException {
    	HttpPost httpPost = null;// 创建get请求
    	HttpClient httpClient = null;
		HttpResponse response = null;
		HttpEntity entity = null;
		String responseContent = null;
		JSONObject retObj = null;
		try {
			// 创建默认的httpClient实例.
			httpClient = new DefaultHttpClient();
			// 执行请求
			boolean isOut = false;
			while(true){
				if(isOut) break;
				String httpUrl = "http://restapi.amap.com/v3/place/text";
				httpPost = new HttpPost(httpUrl);
				//设置头
				httpPost.addHeader("User-Agent","AMAP SDK Android Search 5.0.0");
				httpPost.addHeader("Content-Type","application/x-www-form-urlencoded");
				httpPost.addHeader("Accept-Encoding", "");
				httpPost.addHeader("Connection", "close");
				httpPost.addHeader("Host", "restapi.amap.com");
				
				//设置体
				
				List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); 
				Map<String, String> maps = new HashMap<String,String>();
				maps.put("output", "json");
				if(address.contains("北京")){
					maps.put("city", "110100");
				}
				maps.put("keywords", address+CustomAppName.getRandomChar());
				maps.put("language", "zh-CN");
				maps.put("offset", "20");
				maps.put("page", "1");
				maps.put("types", "");
				maps.put("extensions", "all");
				maps.put("key", "f4ec82d1f9d5ba34a37eeb2119f83a07");
				maps.put("citylimit", "false");
				maps.put("children", "0");
				maps.put("ts", System.currentTimeMillis()+"");
				maps.put("scode", "ebb8e34673cbf455e8f8c39ba8e56ef9");
		        for (String key : maps.keySet()) {  
		            nameValuePairs.add(new BasicNameValuePair(key, maps.get(key)));  
		        }  
		        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
				
				response = httpClient.execute(httpPost);
				entity = response.getEntity();  
				responseContent = EntityUtils.toString(entity, "UTF-8");  
				System.out.println(responseContent);
				
				JSONObject myObject = JSONObject.parseObject(responseContent);
				JSONArray tips = myObject.getJSONArray("pois");
				
				if(tips!=null && tips.size()>0){
					
					for(int i=0;i<tips.size();i++){
						JSONObject tipsi = tips.getJSONObject(i);
						System.out.println(tipsi);
						String pname = tipsi.getString("pname");
						String cityname = tipsi.getString("cityname");
						String adname = tipsi.getString("adname");
						if(address.contains(adname)&&tipsi.getString("address")!=null&&!"".equals(tipsi.getString("address"))&&!"[]".equals(tipsi.getString("address"))){
							System.out.println(pname+cityname+adname+"--"+tipsi.getString("name")+"--"+tipsi.getString("location")+"--"+tipsi.getString("address"));
							if(!tipsi.getString("name").contains("公交")&&!tipsi.getString("name").contains("地铁")&&tipsi.getString("address").length()>6) {
								retObj = tips.getJSONObject(i);
								isOut = true;
								break;
							}
						}
					}
				}
			}
        	
		}catch(Exception e){
			e.printStackTrace();
		}
		return retObj;
    }
    public JSONObject getAddress1(String address) throws UnsupportedEncodingException {
    	HttpGet httpGet = null;// 创建get请求
    	HttpClient httpClient = null;
		HttpResponse response = null;
		HttpEntity entity = null;
		String responseContent = null;
		JSONObject retObj = null;
		try {
			// 创建默认的httpClient实例.
			httpClient = new DefaultHttpClient();
			// 执行请求
			boolean isOut = false;
			while(true){
				if(isOut) break;
				String httpUrl = "https://restapi.amap.com/v3/assistant/inputtips?s=rsv3&key=462f27e00614a30baa9ed1864455213f&city=&callback=jsonp_932577_&platform=JS&logversion=2.0&sdkversion=1.4.0&appname=https://www.cmaotai.com/ysh5/page/PersonalCenter/Address/addAddress.html?datas=1&csid=4573AA39-D2F9-4942-9B68-12BD116F03E9&keywords="+address+CustomAppName.getRandomChar();
		    	httpGet = new HttpGet(httpUrl);
				
				response = httpClient.execute(httpGet);
				entity = response.getEntity();  
				responseContent = EntityUtils.toString(entity, "UTF-8");  
				System.out.println(responseContent);
				responseContent = responseContent.replace("jsonp_932577_(", "");
				responseContent = responseContent.substring(0, responseContent.length()-1);
				
				JSONObject myObject = JSONObject.parseObject(responseContent);
				JSONArray tips = myObject.getJSONArray("tips");
				
				if(tips!=null && tips.size()>0){
					
					for(int i=0;i<tips.size();i++){
						JSONObject tipsi = tips.getJSONObject(i);
						System.out.println(tipsi);
						String district = tipsi.getString("district");
						if(address.contains(district)&&tipsi.getString("address")!=null&&!"".equals(tipsi.getString("address"))&&!"[]".equals(tipsi.getString("address"))){
							System.out.println(district+"--"+tipsi.getString("name")+"--"+tipsi.getString("location")+"--"+tipsi.getString("address"));
							if(!tipsi.getString("name").contains("公交")&&!tipsi.getString("name").contains("地铁")&&tipsi.getString("address").length()>6) {
								retObj = tips.getJSONObject(i);
								isOut = true;
								break;
							}
						}
					}
				}
			}
        	
		}catch(Exception e){
			e.printStackTrace();
		}
		return retObj;
    }
    public static void main(String[] args) throws Exception{
    	MaotaiAppHttpClientUtil hcu = MaotaiAppHttpClientUtil.getInstance();
    	JSONObject temp = hcu.getAddress("北京市北京市朝阳区");
    	System.out.println(temp);
    }
}